package com.example.asset.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.asset.common.Constants;
import com.example.asset.common.Result;
import com.example.asset.entity.SysUser;
import com.example.asset.entity.SysUserRole;
import com.example.asset.entity.dto.SysUserDao;
import com.example.asset.entity.param.ParamBase;
import com.example.asset.entity.param.ParamBaseExt;
import com.example.asset.service.SysUserRoleService;
import com.example.asset.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Tag(name = "用户管理")
@RestController
@RequestMapping("/sysuser")
@RequiredArgsConstructor
public class SysUserController{

    private final SysUserService sysUserService;
    private final SysUserRoleService userRoleService;

    /**
     * 用于翻页
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Operation(summary = "分页")

    @GetMapping("/page")
    public Result Page(@RequestParam @Parameter(description = "页数") Integer pageNum, @RequestParam @Parameter(description = "页面大小") Integer pageSize, @RequestParam(defaultValue = "") @Parameter(description = "loginName模糊查询") String loginName){
        IPage<SysUser> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(SysUser::getLoginName, loginName).or().like(SysUser::getUserName, loginName);
        IPage<SysUser> userIPage = sysUserService.page(page, queryWrapper);
        return Result.success(userIPage);
    }

    /**
     * 用于添加用户信息
     *
     * @param sysUser
     * @return
     */
    @PostMapping
    @Operation(summary = "添加用户信息")
    public Result save(@RequestBody SysUser sysUser){
        return Result.success(sysUserService.saveUser(sysUser));
    }

    /**
     * 用于删除指定单个用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除指定单个用户")
    public Result delete(@PathVariable Integer id){
        return Result.success(sysUserService.removeById(id));
    }

    /**
     * 用于批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    @Operation(summary = "用于批量删除")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(sysUserService.removeBatchByIds(ids));
    }


    /**
     * 根据登录名查找用户昵称
     *
     * @param loginName
     * @return
     */
    @GetMapping("/username/{loginName}")
    @Operation(summary = "根据登录名查找用户昵称")
    public Result findOne(@PathVariable String loginName){
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", loginName);
        SysUser one = sysUserService.getOne(queryWrapper);
        one.setPassword(null);
        one.setSalt(null);
        return Result.success(one);
    }


    /**
     * 导出用户信息
     *
     * @param response
     * @throws Exception
     */
    @Operation(summary = "导出用户信息")
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
        // 从数据库查询出所有的数据
        List<SysUser> list = sysUserService.list();

        ExcelWriter writer = ExcelUtil.getWriter(true);

        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * excel 导入
     *
     * @param file
     * @throws Exception
     */
    @Operation(summary = "导入用户信息")
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        //@Alias解决英文表头的问题
        List<SysUser> list = reader.readAll(SysUser.class);
        System.out.println(list);
        sysUserService.saveBatch(list);

        return true;
    }

    @Operation(summary = "用于登录")
    @PostMapping("/login")
    public Result login(@RequestBody SysUserDao sysUserDao, HttpServletRequest request){

        String username = sysUserDao.getLoginName();
        String password = sysUserDao.getPassword();

        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400, "参数错误");
        }

        SysUserDao dao = sysUserService.login(sysUserDao, request);
        return Result.success(dao);

    }


    // @Operation(summary = "注册")
    // @PostMapping("/register")
    // public Result Register(@RequestBody SysUserDao sysUserDao){
    //     String loginName = sysUserDao.getLoginName();
    //     String password = sysUserDao.getPassword();
    //     if(StrUtil.isBlank(loginName) || StrUtil.isBlank(password)){
    //         return Result.error(Constants.CODE_400, "参数错误");
    //     }
    //     return Result.success(sysUserService.register(sysUserDao));
    // }

    @PostMapping("/listUserRole")
    public Result Register(@RequestBody ParamBase param){
        List<SysUserRole> list = userRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, param.getId()));
        return Result.success(list);
    }

    @PostMapping("/saveUserRole")
    public Result saveUserRole(@RequestBody ParamBaseExt param){
        if(CollectionUtil.isNotEmpty(param.getList()) && param.getCode() != null){
            userRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, param.getCode()));
            List<SysUserRole> list = new ArrayList<>(param.getList().size());
            param.getList().forEach(f -> {
                list.add(new SysUserRole(param.getCode().longValue(), f, null));
            });
            userRoleService.saveBatch(list);
        }

        return Result.success(true);
    }
}